package cn.com.digitalnet.ad.search;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.google.common.collect.Maps;

public class SearchFilterBuilder {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 */
	public static Map<String, SearchFilter> build(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			if (StringUtils.isBlank((String) value)) {
				continue;
			}

			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String operatorName = names[0];
			//对日期字段的处理
			if(operatorName.endsWith("D")){
				try{
					value = DATE_FORMAT.parse((String)value);
					operatorName = operatorName.substring(0, operatorName.length() - 1);
				}catch(Exception e){
					throw new RuntimeException(e);
				}
			}
			String fieldName = names[1];
			Operator operator = Operator.valueOf(operatorName);

			// 创建searchFilter
			SearchFilter filter = new SearchFilter(fieldName, operator, value);
			filters.put(key, filter);
		}

		return filters;
	}
}
